package web.action.com;

import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Maps;
import com.joint.base.entity.Company;
import com.joint.base.entity.Users;
import com.joint.base.parent.BaseEntity;
import com.joint.base.service.ExportService;
import com.joint.base.service.activiti.WorkflowQueryService;
import com.joint.base.util.ExportUtil;
import com.joint.base.util.StringUtils;
import com.joint.base.util.excel.annotation.ExcelField;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import web.FlowInfo;
import web.action.BaseAdminAction;

import javax.annotation.Resource;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: xuzhou
 * Date: 2015/4/2
 * Time: 16:02
 * 导出表格的action
 */
public class AjaxExportAction extends BaseAdminAction {
    @Resource
    protected RepositoryService repositoryService;
    //导出
    @Resource
    protected ExportService exportService;
    @Resource
    protected FreeMarkerConfig freeMarkerConfig;
    @Resource
    protected WorkflowQueryService workflowQueryService;
    //前台传送的字段
    private String code;

    //树形菜单

    /**
     * 1.从流程定义中读取数据读取最新版本
     * 2.判断是否存在对应的class
     * 3.读取对应class中的注解信息
     * @return
     * @throws Exception
     */
    public String zTree() throws Exception {
        List<JSONObject> treeList = new ArrayList<JSONObject>();
        for (ProcessDefinition per : workflowQueryService.findProcessDefinition()) {
            Map<String, Object> rMap = new HashMap<String, Object>();
            String className = FlowInfo.ENTITY_PACKAGE+ StringUtils.upperFirst(per.getKey());
            Class clazz;
            try {
                clazz = Class.forName(className);
            } catch (ClassNotFoundException e) {
                LogUtil.info(className + "找不到");
                continue;
            }
            rMap.put("id", per.getKey());
            rMap.put("pId", "");
            rMap.put("pName", per.getName());
            rMap.put("name", per.getName());
            rMap.put("sName", per.getName());
            rMap.put("intLevel", "1");
            rMap.put("open", false);
            treeList.add(JSONObject.fromObject(rMap));

            //加入父类中的注解
            Field[] fields = clazz.getDeclaredFields();
            for (Field pf : clazz.getFields()) {
                fields = ArrayUtils.add(fields, pf);
            }
            for(Field f : fields){
                ExcelField ef = f.getAnnotation(ExcelField.class);
                if(ef == null){
                    continue;
                }
                rMap.put("id", f.getName());
                rMap.put("pId", per.getKey());
                rMap.put("pName", f.getName());
                rMap.put("name", ef.title());
                rMap.put("sName", f.getName());
                rMap.put("intLevel", "2");
                rMap.put("open", false);
                treeList.add(JSONObject.fromObject(rMap));
            }

        }
        Map<String, Object> data = new HashMap<String, Object>();
        data = new HashMap<String, Object>();
        data.put("data", JSONArray.fromObject(treeList));
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

    //导出表格
    public String export() throws Exception {
        //再把需要用到的字段拆出来
        String name[] = keyIds.split(",");
        Company company = usersService.getCompanyByUser();
        List<BaseEntity> baseEntityList = exportService.getAll(company, "ProStart");

        List<Object> listo = new ArrayList<Object>();
        Map<String, Object> proMap = Maps.newHashMap();
        List<String> objs = null;
        //先把标题拆出来
        String title[] = keyNames.split(",");
        for (int i = 0; i < baseEntityList.size(); i++) {
            Object object = baseEntityList.get(i);
            objs = new ArrayList<>();
            //获取这个类所有声明的字段
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field pf : object.getClass().getFields()) {
                fields = ArrayUtils.add(fields, pf);
            }
            //字段循环和前台选中的字段判断
            for (int k = 0; k < fields.length; k++) {
                fields[k].setAccessible(true);
                String n = fields[k].getName();
                //循环前台获取的字段
                for (int l = 0; l < name.length; l++) {
                    String zd = name[l];
                    if (n.equals(zd)) {
                        try {
                            Object objects = fields[k].get(object);
                            String vales = null;
                            if (objects instanceof Users) {
                                //user = (Users) objects;
                                //vales = user.getName();
                            } else {
                                if (objects != null) {
                                    vales = objects.toString();
                                }
                            }
                            objs.add(vales);
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            listo.add(objs);
        }

        proMap.put("prosize", baseEntityList.size() + 5 * 10);
        proMap.put("title", title);// 自定义字段标题
        proMap.put("listo", listo);//自定义字段
        String fileName = "项目立案";
        new ExportUtil("ProStart", freeMarkerConfig).setDataList(proMap).exportExcel(this.getResponse(), fileName, getRequest());
        return ajaxHtmlCallback("200", "导出成功！", "操作状态");
    }


    /**
     * ********
     * 根据包名来获取此包下所有的类名及其实例
     *
     * @param packName
     * @return
     */
    public static Set<Object> getObjectsInPackage(String packName) {
        Set<Object> objs = new HashSet<Object>();
        String packageName = packName;
        String packageDirName = packageName.replace(".", "/");
        Enumeration<URL> dirs = null;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            //迭代此 Enumeration
            while (dirs.hasMoreElements()) {
                URL url = dirs.nextElement();
                File file = new File(url.getFile());
                //把此目录下的所有文件列出
                String[] classes = file.list();
                //循环此数组，并把.class去掉
                for (String className : classes) {
                    className = className.substring(0, className.length() - 6);
                    //拼接上包名，变成全限定名
                    String qName = packageName + "." + className;
                    //如有需要，把每个类生实一个实例
                    Object obj = Class.forName(qName).newInstance();
                    //添加到集合中
                    objs.add(obj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return objs;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}
